package com.xyc.attend.service;

import com.xyc.attend.dao.AttendMapper;
import com.xyc.attend.entity.Attend;
import com.xyc.common.utils.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service("attendServiceImpl")
public class AttendServiceImpl implements AttendService {

    /**
     * 中午12点 用于判定上下午
     */
    private static final int NOON_MINUTE = 00;
    private static final int NOON_HOUR = 12;

    private Log log = LogFactory.getLog(AttendServiceImpl.class);

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Autowired
    private AttendMapper attendMapper;

    @Override
    public void signAttend(Attend attend) throws Exception {


        try {
            Date today = new Date();
            attend.setAttendDate(today);
            attend.setAttendWeek((byte) DateUtils.getTodayWeek());
            //查询当天此人有没打卡记录
            Attend todayRecord = attendMapper.selectTodaySignRecord(attend.getUserId());
            Date noon = DateUtils.getDate(NOON_HOUR, NOON_MINUTE);
            if (todayRecord == null) {
                //打卡记录不存在
                if (today.compareTo(noon) <= 0) {
                    //打卡时间早于12点 上午打卡
                    attend.setAttendMorning(today);
                } else {
                    //晚上打卡
                    attend.setAttendEvening(today);
                }
                attendMapper.insertSelective(attend);
            } else {
                if (today.compareTo(noon) <= 0) {
                    //打卡时间早于12点 上午打卡
                    return;
                } else {
                    //晚上打卡
                    todayRecord.setAttendEvening(today);
                    attendMapper.updateByPrimaryKeySelective(todayRecord);
                }
            }

            //中午十二点前打卡算上午打卡。  9点30后算迟到，异常
            // 十二点后打卡算下午打卡 检查和上午的时间差 不足8小时算异常，并记录缺席时间。18点之前早退算异常
        } catch (Exception e) {
            log.error("用户签到异常", e);
            throw e;
        }
    }
}
